
from main.exceptions.exception import EmptyPCBListException, EmptyPCBManagerException
from main.model.pcb_management.pcb_list import PCBList
from main.model.pcb_management.pcb_manager import PCBManager


class PCBManagerSmart(PCBManager):

    """Initialize lists with one item
    then extends the collection to the maximum priority handled"""
    def __init__(self, _max_priority = 5):
        self.__current_max_priority = 0
        self.__pcb_lists            = [PCBList(self.__current_max_priority)]
        self.__extend_lists_to(_max_priority)
    
    def __extend_lists_to(self, max_priority):
        for priority in range(self.__current_max_priority + 1, max_priority + 1):
            self.__pcb_lists.append(PCBList(priority))
        self.__current_max_priority = max_priority
        
    def next(self):
        for index in range(self.__current_max_priority, -1, -1):
            try:
                return self.__pcb_lists[index].next()
            except EmptyPCBListException:
                pass
        raise EmptyPCBManagerException

    def add(self, pcb):
        if(self.__current_max_priority < pcb.inner_priority):
            self.__extend_lists_to(pcb.inner_priority)
        self.__pcb_lists[pcb.inner_priority].add(pcb)
   
    def has_next(self):
        for pcb_list in self.__pcb_lists:
            if(pcb_list):
                return True
        return False
        
        